import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../components/login.vue'
import home from '../components/home.vue'
import welcome from '../components/Welcome.vue'

import users from '../components/user/users.vue'
import Rights from '../components/power/Rights.vue'
import Roles from '../components/power/Roles.vue'
import Cate from '../components/goods/cate.vue'

import Params from '../components/goods/Params.vue'

import goodsList from '../components/goods/List.vue'

import goodsAdd from '../components/goods/Add.vue'
import order from '../components/order/Order.vue'

import report from '../components/report/report.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: login },
  {
    path: '/home', component: home, redirect: '/welcome', children: [
      { path: '/welcome', component: welcome },
      { path: '/users', component: users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Cate },
      { path: '/params', component: Params },
      { path: '/goods', component: goodsList },
      { path: '/goods/add', component: goodsAdd },
      { path: '/orders', component: order },
      { path: '/reports', component: report }
    ]
  }
]

const router = new VueRouter({
  routes
})



// 路由守卫，登录拦截,防止用户直接访问主页
router.beforeEach((to, from, next) => {
  // to 表示要跳转到哪一个页面
  // form 表示从哪一个跳转的
  // next 表示放行
  // next()  next('/login')
  // 首先判断是要跳转到登录页面
  if (to.path == '/login') return next()
  // 如果不是跳转到登录页面，那就获取一下token，判断是否携带token字符串
  const tokenstr = window.sessionStorage.getItem('token')
  // 如果token不存在，则强制跳转到login页面
  if (!tokenstr) return next('/login')
  next()

})

export default router
